package org.elec.mac.tag;

import org.elec.mac.constants.Constants;
import org.elec.mac.ehcache.CacheConfiguration;
import org.elec.mac.entity.SessionUser;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Created by Bean on 2017/5/26.
 */
public class UserNameTag {

    private static CacheConfiguration cacheConfiguration;

    public static void getInstance() {
        if(ObjectUtils.nullSafeEquals(cacheConfiguration, null)) {
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(attr.getRequest().getSession().getServletContext());
            cacheConfiguration = applicationContext.getBean(CacheConfiguration.class);
        }
    }

    /**
     * 用户菜单
     * @return
     */
    public static String getUserName() {
        getInstance();
        EhCacheCacheManager manager
                = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        SessionUser sessionUser = (SessionUser) attr.getRequest().getSession().getAttribute(Constants.SESSION_USER_KEY);
        Cache authorityCache = manager.getCache("authorityCache");
        return authorityCache.get(sessionUser.getToken(), String.class);
    }

    /**
     * 判断是否为超级管理员
     * @param username
     * @return
     */
    public static Boolean getSysManager(String username) {
        //
        if (username.equals(Constants.SYSTEM_ADMIN)) {
            return true;
        }
        return false;
    }

    /**
     *
     * @return
     */
    public static String getSystemAdmin() {
        return Constants.SYSTEM_ADMIN;
    }
}
